#include "vsLogic.h"
#include "ui/vsTelnet.h"
#include <QDebug>
#include <QTime>


#define VOCASEED_QTGUI // TODO: move to build options or .pro and use for .cpp's with gui

#ifdef VOCASEED_QTGUI
    #include "qtsingleapplication/src/qtsingleapplication.h"
    #include "ui/vsQtGui.h"
    typedef  QtSingleApplication QtSingleApp;
    #define  VS_CONNECT_GUI(x) x.connectUI(new vsQtGui(&x));
#else
    #include "qtsingleapplication/src/qtsinglecoreapplication.h"
    typedef  QtSingleCoreApplication QtSingleApp;
    #define  VS_CONNECT_GUI(x)
#endif


const char const_vsreq_msg[] = "vocaseed_request";


int main(int argc, char *argv[])
{
    QtSingleApp a("VocaSeed", argc, argv);
    QtSingleApp::setQuitOnLastWindowClosed(false);

    // randomizing the randomizer
    QTime t(QTime::currentTime());
    srand(t.second() * t.hour() + 3939);

    if (a.isRunning())
    {
        QString paramStr(const_vsreq_msg);

        for (int i = 1; i < argc; ++i)
            paramStr.append(QString(" %1").arg(argv[i]));

        bool ok = a.sendMessage(paramStr);

        if (!ok)
            qDebug() << "Error: could not send message to an already running instance, "
                     << "it may be frozen or overloaded";

        return !ok; // 0 if ok is true
    }
    else
    {
        vsLogic l;

        VS_CONNECT_GUI(l)
        l.connectUI(new vsTelnet(&l));

        // receive messages from any other future instances of this app
        QObject::connect(&a, SIGNAL(messageReceived(const QString&)), &l, SLOT(onAppMessage(const QString&)));

        return a.exec();
    }
}
